# -*- coding: utf8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import DNS, re
import IPy
import csv
import xlrd
import time

num = 0
def ReadFile(Filename):
    suffix = Filename.split(".")
    if suffix[-1] == "csv":
        data = open(Filename, 'r')
        domainList = []
        x=0
        for i in data.readlines():
           x+=1
           if x>=3:
            domainList.append(i.split(",")[0])
    elif suffix[-1]=="txt":
        data= open(Filename,'r')
        domainList = {}
        for i in data.readlines():
            domainList[i.strip()]="网信分析"
        return domainList
    else:
        print "需要检测文件错误，请重新输入文件！"


f = open('check_to_cname.txt', 'w')
def WrlteFile(domain,start,CP_NAME="无CNAME"):
    WDATA=domain+" "+" "+str(CP_NAME)+" "+start+'\n'
    f.writelines(WDATA)
    print domain + " 分析结果写入文件完成～！"

def FindCNAME(domain):
    DNS.DiscoverNameServers()
    reqobj = DNS.Request()
    try:
        print domain
        answerobj = reqobj.req(domain)  #这句
        x = answerobj.answers
    except Exception,e:
        print e
        return  "none"
    for donequeries in x:
        if donequeries['typename']=="CNAME": #判断是否含有CNAME
            answers = []
            i=[]
            re_ip = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') #判断IP
            for i in x:
                if not re_ip.match(i['data']):#直到IP停止
                    answers=i['data']
            if len(answers) != 0:
                if i['data'] in IPy.IP("113.214.0.0/15"):
                    answers=answers+" "+"网内已经覆盖"
                elif i['data'] in IPy.IP("43.247.232.0/22"):
                    answers=answers+" "+"网内已经覆盖"
                else:
                    answers=answers+" "+"域名出网"
            return answers #返回最后一个CNAME
        else:
            if donequeries['data'] in IPy.IP("113.214.0.0/15"):
                return  "none" + " " + "网内已经覆盖"
            else:
                return   "none" + " " + "域名出网"


def ProcessData(cname):
    types = {
        "蓝讯": ["ccgslb.net", "ccgslb.com", "ccgslb.com.cn", "chinacache.net", "chinacache.com.cn", "lxsvc.cn"],
        "网宿": ["glb0.lxdns.com", "ourdvs.com", "ourwebpic.com", "ourwebcdn.com", "ourglb0.com", "ourwebhttps.com",
               "ourwebat.com"],
        "快网": ["fastweb.com", "fastwebcdn.com", "cloudcdn.net", "cloudglb.com", "cachecn.com", "cachecn.net",
               "hadns.net", "hacdn.net"],
        "帝联": ["dnion.com", "ewcache.com", "globalcdn.cn", "tlgslb.com", "fastcdn.com"],
        "百度": ["jomodns.com"],
        "京东": ["jdcdn.com"],
             "淘宝":["alikunlun.com"
                        ,"alikunlun.net"
                        ,"kunlunaq.com"
                        ,"kunlunar.com"
                        ,"kunlunca.com"
                        ,"kunluncan.com"
                        ,"kunlunea.com"
                        ,"kunlungem.com"
                        ,"kunlungr.com"
                        ,"kunlunhuf.com"
                        ,"kunlunle.com"
                        ,"kunlunli.com"
                        ,"kunlunno.com"
                        ,"kunlunpi.com"
                        ,"kunlunra.com"
                        ,"kunlunsa.com"
                        ,"kunlunsc.com"
                        ,"kunlunsl.com"
                        ,"kunlunso.com"
                        ,"kunlunta.com"
                        ,"kunlunvi.com"
                        ,"kunlunwe.com"
                        ,"alicdn.com"
                        ,"tbcache.com"
                        ],    
        "新浪": ["sinaedge.com"],
        "爱奇艺": ["dns.iqiyi.com"],
        "PPTV": ["cloudxns.pptv.com"],
        "腾讯":["tc.qq.com","tcdn.qq.com","myqcloud.com","dayugslb.com","tencent-cloud.net","tcdnvod.com","tcdnlive.com","cdntip.com"],
        "沙塔": ["satacdn.com", "sihuacdn.com.cn", "okeycdn.com"],
        "云帆": ["yflive.net", "yunfancdn.com"],
        "金山云": ["ks-cdn.com", "ksyuncdn.com"],
        "白山云": ["qingcdn.com", "bsgslb.com", "trpcdn.net", "bsgslb.cn", "bsclink.cn"],
        "迅雷星域": ["p2cdn.com", "00cdn.com", "xycdn.com"],
        "又拍云": ["b0.upaiyun.com", "b0.aicdn.com"],
        "小米": ["mgslb.com"],
        "乐视云": ["gslb.lecloud.com", "lsyun.net", "cdnle.com"],
    }
    all={}
    for t in types.iteritems():
        for hz in t[1]:
            all[hz]=t[0]
        for type in all.iteritems():
            if len(cname.split(type[0]))==2:
                return type[1]
    return "CNAME不在服务列表中"





if __name__=="__main__":
    #读取文件返回字典{域名：公司名}
    filename=sys.argv[1]
    #ilename=raw_input()
    print "读取文件：" + str(filename)
    domainList = ReadFile(filename)
    data=[]
    i=1
    for domain in domainList:
        answers = FindCNAME(domain)
        if not answers.split()[0]=="none"and answers.split()[0]:
            CP_NAME=ProcessData(answers.split()[0])
        else:
            CP_NAME="无CNAME"
        #print(len(answers.split()))
        #if len(answers.split())==2:
        WrlteFile(domain,answers.split()[1],CP_NAME)
